﻿#include "customgraphicsview.h"

#include "customrectitem.h"
#include <QContextMenuEvent>
#include <QGraphicsItem>
#include <QDebug>

CustomGraphicsView::CustomGraphicsView(QWidget *parent)
    : QGraphicsView(parent)
{
    // 允许拖拽选择（橡皮筋选择）
    setDragMode(QGraphicsView::RubberBandDrag);
}

void CustomGraphicsView::mousePressEvent(QMouseEvent *event)
{
    // 修正点 2：对于左键点击，我们必须调用基类的实现，
    // 这是让 QGraphicsItem 的移动 (ItemIsMovable) 和标准选择功能生效的关键。
    // 之前的实现拦截了此事件，导致移动功能被破坏。
    if (event->button() == Qt::LeftButton) {
        QGraphicsView::mousePressEvent(event);
        // 调用基类后，选择和准备移动的逻辑由Qt内部处理，我们不再需要自定义代码。
    }
    // 对于右键，我们仍然保持原来的逻辑，即什么都不做，
    // 以防止在弹出菜单前改变当前的选择状态。
    else if (event->button() == Qt::RightButton) {
        // 此处为空，是正确的，可以保留选择并触发 contextMenuEvent
    }
    // 其他鼠标按键，也交由基类处理。
    else {
        QGraphicsView::mousePressEvent(event);
    }
}


// 重写的右键菜单事件
void CustomGraphicsView::contextMenuEvent(QContextMenuEvent *event)
{
    // 1. 记录右键点击的场景坐标，供“添加字符”功能使用
    m_contextMenuScenePos = mapToScene(event->pos());

    QMenu menu(this);
    // 2. 创建所有菜单项
    QAction *addAction = menu.addAction("添加字符");
    QAction *deleteAction = menu.addAction("删除字符");
    menu.addSeparator();
    QAction *editAction = menu.addAction("编辑矩形");
    QAction *finishEditAction = menu.addAction("完成编辑");
    menu.addSeparator();
    QAction *mergeAction = menu.addAction("合并矩形");
    QAction *splitHAction = menu.addAction("水平分割");
    QAction *splitVAction = menu.addAction("垂直分割");

    QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
    int selectionCount = selectedItems.size();

    // 3. 根据逻辑启用/禁用菜单项

    // 添加操作：总是可用
    addAction->setEnabled(true);

    // 删除操作：只要有选中项就可用
    deleteAction->setEnabled(selectionCount > 0);

    // 合并操作：需要选中至少2个矩形
    mergeAction->setEnabled(selectionCount > 1);

    // 编辑、完成编辑、分割操作默认为禁用
    editAction->setEnabled(false);
    finishEditAction->setEnabled(false);
    splitHAction->setEnabled(false);
    splitVAction->setEnabled(false);

    if (selectionCount == 1) {
        // 当只选中一个矩形时
        CustomRectItem *item = qgraphicsitem_cast<CustomRectItem*>(selectedItems.first());
        if (item) {
            // 根据当前是否为编辑模式，决定启用“编辑”还是“完成编辑”
            editAction->setEnabled(!item->isEditable());
            finishEditAction->setEnabled(item->isEditable());

            // 只有在非编辑模式下才能进行分割
            bool canSplit = !item->isEditable();
            splitHAction->setEnabled(canSplit);
            splitVAction->setEnabled(canSplit);
        }
    }

    // 4. 连接信号槽
    connect(addAction, &QAction::triggered, this, &CustomGraphicsView::addRect);
    connect(deleteAction, &QAction::triggered, this, &CustomGraphicsView::deleteSelectedRects);
    connect(editAction, &QAction::triggered, this, &CustomGraphicsView::toggleEditMode);
    connect(finishEditAction, &QAction::triggered, this, &CustomGraphicsView::toggleEditMode);
    connect(mergeAction, &QAction::triggered, this, &CustomGraphicsView::mergeSelectedRects);
    connect(splitHAction, &QAction::triggered, this, &CustomGraphicsView::splitHorizontally);
    connect(splitVAction, &QAction::triggered, this, &CustomGraphicsView::splitVertically);

    // 5. 显示菜单
    menu.exec(event->globalPos());
}

void CustomGraphicsView::toggleEditMode()
{
    QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
    if (selectedItems.size() != 1) return;

    CustomRectItem *item = qgraphicsitem_cast<CustomRectItem*>(selectedItems.first());
    if (item) {
        item->setEditable(!item->isEditable());
    }
}

void CustomGraphicsView::mergeSelectedRects()
{
    QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
    if (selectedItems.size() <= 1) return;

    QRectF totalRect;
    bool first = true;

    for (QGraphicsItem *item : selectedItems) {
        if (first) {
            totalRect = item->sceneBoundingRect();
            first = false;
        } else {
            totalRect = totalRect.united(item->sceneBoundingRect());
        }
    }

    // 先复制一份列表，因为 removeItem 会修改 selectedItems
    QList<QGraphicsItem*> itemsToRemove = selectedItems;
    for (QGraphicsItem *item : itemsToRemove) {
        scene()->removeItem(item);
        delete item;
    }

    CustomRectItem *mergedRect = new CustomRectItem(totalRect);
    scene()->addItem(mergedRect);
}

void CustomGraphicsView::addRect()
{
    // 定义一个默认的矩形大小
    qreal width = 100.0;
    qreal height = 60.0;
    // 以鼠标点击位置为中心创建矩形
    QRectF newRect(m_contextMenuScenePos.x() - width / 2,
                   m_contextMenuScenePos.y() - height / 2,
                   width, height);

    CustomRectItem *item = new CustomRectItem(newRect);
    scene()->addItem(item);
}

void CustomGraphicsView::deleteSelectedRects()
{
    // 必须先复制列表，因为 removeItem 会修改 selectedItems() 返回的列表
    QList<QGraphicsItem*> itemsToRemove = scene()->selectedItems();
    for (QGraphicsItem *item : itemsToRemove) {
        scene()->removeItem(item);
        delete item; // 释放内存
    }
}

void CustomGraphicsView::splitHorizontally()
{
    QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
    if (selectedItems.size() != 1) return;

    CustomRectItem *itemToSplit = qgraphicsitem_cast<CustomRectItem*>(selectedItems.first());
    if (!itemToSplit || itemToSplit->isEditable()) return;

    // 使用之前修复的正确坐标计算方法
    QRectF localRect = itemToSplit->boundingRect();
    QPointF position = itemToSplit->pos();
    QRectF sceneRect(position + localRect.topLeft(), localRect.size());

    scene()->removeItem(itemToSplit);
    delete itemToSplit;

    // 水平分割（上下）
    QRectF rect1(sceneRect.topLeft(), QSizeF(sceneRect.width(), sceneRect.height() / 2));
    QRectF rect2(sceneRect.left(), sceneRect.top() + sceneRect.height() / 2, sceneRect.width(), sceneRect.height() / 2);

    CustomRectItem *newRect1 = new CustomRectItem(rect1);
    CustomRectItem *newRect2 = new CustomRectItem(rect2);
    scene()->addItem(newRect1);
    scene()->addItem(newRect2);
}

void CustomGraphicsView::splitVertically()
{
    QList<QGraphicsItem*> selectedItems = scene()->selectedItems();
    if (selectedItems.size() != 1) return;

    CustomRectItem *itemToSplit = qgraphicsitem_cast<CustomRectItem*>(selectedItems.first());
    if (!itemToSplit || itemToSplit->isEditable()) return;

    // 同样使用正确的坐标计算方法
    QRectF localRect = itemToSplit->boundingRect();
    QPointF position = itemToSplit->pos();
    QRectF sceneRect(position + localRect.topLeft(), localRect.size());

    scene()->removeItem(itemToSplit);
    delete itemToSplit;

    // 垂直分割（左右）
    QRectF rect1(sceneRect.topLeft(), QSizeF(sceneRect.width() / 2, sceneRect.height()));
    QRectF rect2(sceneRect.left() + sceneRect.width() / 2, sceneRect.top(), sceneRect.width() / 2, sceneRect.height());

    CustomRectItem *newRect1 = new CustomRectItem(rect1);
    CustomRectItem *newRect2 = new CustomRectItem(rect2);
    scene()->addItem(newRect1);
    scene()->addItem(newRect2);
}
